<?php
namespace Appstore\Widget;

use Think\Controller;

class PayWidget extends Controller
{
    private function getAmount($order){
        $finally =$order['payment_price'];
        $score_id=$order['score'];
        $fields_config = modC('RE_FIELD', "", 'recharge');
        $fields = json_decode($fields_config,true);
        $type = array_search_key($fields,'FIELD',$score_id);
        if( !$type){
            return 0;
        }
        return number_format($finally/$type['UNIT'], 2, ".", "");
    }

    public function pay($order_id){
        $link = D('order_link')->where(array('order_id'=>$order_id))->cache(60)->find();
        $order = D($link['model'])->where(array('id'=>$order_id))->find();

        $goods=D('AppstoreGoods')->find($order['goods_id']);
        $this->assign('title',$goods['title']);
        $this->assign('amount',$this->getAmount($order));
        $this->assign('order_id',$order_id);
        $this->display(T('Application://Appstore@Widget/pay'));
    }


    public function beforePayAlipay($order_id){
        $link = D('order_link')->where(array('order_id'=>$order_id))->cache(60)->find();
        $order = D($link['model'])->where(array('id'=>$order_id))->find();
        $return['total_fee'] =  $this->getAmount($order);
        $return['out_trade_no'] = $order_id;
        return $return;
    }



    public function afterPayAlipay($record){

        $order_id = $record['out_trade_no'];
        //交易状态
        if ($record['trade_status'] == 'TRADE_FINISHED' || $record['trade_status'] == 'TRADE_SUCCESS') {

            D('Appstore/AppstoreOrder')->afterPay($order_id);

           return('付款成功');
        } else {
            return('失败——支付状态出错。' . $record['trade_status'] . $order_id);
            /* $this->error('支付状态出错。' . $record['trade_status']);*/
        }
    }

}